#include <iostream>
#include <pthread.h>
#include <unistd.h>
int tickets = 10000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *start_routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        // pthread_mutex_lock(&lock);
        // pthread_cond_wait(&cond,&lock);
        // if (tickets > 0)
        // {
        //     usleep(1254);
        //     printf("%s->%d\n", name.c_str(), tickets--);
        //     pthread_mutex_unlock(&lock);
        // }
        // else
        // {
        //     pthread_mutex_unlock(&lock);
        //     break;
        // }
        while (true)
        {
            pthread_mutex_lock(&lock);
            pthread_cond_wait(&cond, &lock);
            printf("%s->%d\n", name.c_str(), tickets--);
            pthread_mutex_unlock(&lock);
        }
    }
}
int main()
{
    pthread_t t[5];
    for (int i = 0; i < 5; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "thread %d", i + 1);
        pthread_create(t + i, nullptr, start_routine, (void *)name);
    }
    while (true)
    {
        sleep(1);
        // pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        printf("main thread wakeup one thread...\n");
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(t[i], nullptr);
    }
}